<template>
    <div class="user-wapper">
      <el-breadcrumb separator-class="el-icon-arrow-right" class="el-bread-group">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
        <el-card class="user-table">
          <el-row :gutter="20">
          <el-col :span="8">
            <el-input placeholder="请输入搜索内容" v-model="queryData.query" clearable @clear='getUsers'>
              <el-button slot="append" icon="el-icon-search" @click="getQueryAboutList"></el-button>
            </el-input>
          </el-col>
          <el-col :span="6"><el-button type="primary" @click="dialogAddVisible = true">添加用户</el-button></el-col>
          </el-row>
        <el-table
            :data="userList.users"
            style="width: 100%"
            border
            >
            <el-table-column
            label="#"
            type="index"> </el-table-column>
            <el-table-column
            label="姓名"
            prop="username"> </el-table-column>
            <el-table-column
            label="角色"
            prop="role_name"></el-table-column>
            <el-table-column
            label="手机号"
            prop="mobile"></el-table-column>
            <el-table-column
            label="邮箱"
            prop="email"></el-table-column>
            <el-table-column
            prop="mg_state"
            label="状态"
            width="100">
              <template v-slot="scope">
                <el-tooltip :enterable="false" :content="(scope.row.mg_state?'已激活':'未激活')" placement="top">
                  <el-switch
                    :disabled="false"
                    v-model="scope.row.mg_state"
                    @change="userStateChange(scope.row)">
                  </el-switch>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column
            label="操作"
            align="center">
              <template  slot-scope="scope">
                <el-tooltip class="item" effect="dark" content="编辑" placement="top" :enterable='false'>
                  <el-button type="primary" icon="el-icon-edit" size="small" @click="btnEditUser(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="删除" placement="top" :enterable='false'>
                  <el-button type="danger" icon="el-icon-delete" size="small" @click="btnDeleteClick(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable='false'>
                  <el-button type="success" icon="el-icon-setting" size="small" @click="btnSettingClick(scope.row)"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
        </el-table>
            <div class="div-el-pagination">
              <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              @prev-click="handlePrevChange"
              @next-click="handleNextChange"
              :current-page="queryData.pagenum"
              :page-sizes="[2, 4, 8, 10,12]"
              :page-size="queryData.pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="userList.total">
              </el-pagination>
            </div>
        </el-card>
        <!-- 新增用户信息 -->
        <el-dialog title="新增用户信息" :visible.sync="dialogAddVisible" >
           <!-- dialog主题区域 -->
          <el-form :model="addForm" :rules="addFormRules"
            ref="addFormRef" label-width="70px">
            <el-form-item label="用户名" prop="username" >
              <el-input v-model="addForm.username" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password" >
              <el-input type="password" v-model="addForm.password" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email" >
              <el-input v-model="addForm.email" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile" >
              <el-input v-model="addForm.mobile" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="addDialogClosed">重置</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
          </div>
        </el-dialog>
        <!-- 修改用户 -->
        <el-dialog title="修改用户信息" :visible.sync="dialogEditVisible" @close="addDialogClosed">
          <el-form :model="editForm" ref="editFormRef" @close="editDialogClosed">
            <el-form-item label="用户名" :label-width="formLabelWidth">
              <el-input v-model="editForm.username" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" :label-width="formLabelWidth">
              <el-input v-model="editForm.email" autocomplete="off"></el-input>
            </el-form-item>
             <el-form-item label="手机" :label-width="formLabelWidth">
              <el-input v-model="editForm.mobile" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogEditVisible = false">取 消</el-button>
            <el-button type="primary" @click="editUser(editForm)">确 定</el-button>
          </div>
        </el-dialog>
        <el-dialog title="设置角色" :visible.sync="dialogChangeVisible"  @close='changeDialogClosed'>
          <el-form :model="roleObj" ref="changeFormRef">
            <el-form-item label="角色" :label-width="formLabelWidth">
              <el-select v-model="roleObj.roleId" placeholder="请选择用户角色">
                <el-option :label="role.roleName" :value="role.id" :key="role.id" v-for="role in roleObj.roles"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogChangeVisible = false">取 消</el-button>
            <el-button type="primary" @click="changeRole(roleObj.roleId)">确 定</el-button>
          </div>
        </el-dialog>
    </div>
</template>
<style lang="less" scoped>
    .user-wapper,.el-table{
        margin: 0;
        padding: 0;
    }
    .user-wapper{
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: stretch;
    }
    .user-table{
        margin-left: 10px;
        margin-right: 10px;
        box-shadow: 0,0,1px;
    }
    .div-el-pagination{
        text-align: center;
        margin-top: 20px;
        margin-bottom: 10px;
    }
    .el-bread-group{
      height: 40px;
      line-height: 40px;
      background-color: #E9EEF3;
      padding-left: 10px;
    }
    .el-row{
      height: 40px;
      margin-bottom: 10px;
    }
</style>
<script>
export default {
  created() {
    this.getUsers()
  },
  data() {
    // 验证邮箱规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法邮箱'))
    }
    var checkMobile = (rule, value, callback) => {
      const refMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (refMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法手机号'))
    }
    return {
      search: '',
      userList: {},
      queryData: {
        pagenum: 1,
        pagesize: 10,
        query: ''
      },
      editForm: {},
      formLabelWidth: '80px',
      dialogEditVisible: false,
      addForm: {},
      dialogAddVisible: false,
      dialogChangeVisible: false,
      roleObj: {
        userId: '',
        roleId: '',
        roles: []
      },
      // 添加表单规则验证对象
      addFormRules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 10,
            message: '用户名自长度在3-10之间',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 15,
            message: '密码长度在6-15之间',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱地址',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ]
      },
      editFormRules: {
        email: [
          {
            required: true,
            message: '请输入邮箱地址',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    async getUsers() {
      const params = {
        url: '/users',
        method: 'GET',
        params: this.queryData
      }
      const res = await this.$send(params)
      if (res.meta.status === 200) {
        const data = res.data
        if (data == null) return
        this.userList = data
      }
    },
    async userStateChange (user) {
      const userParams = {
        url: `/users/${user.id}/state/${user.mg_state}`,
        method: 'PUT'
      }
      const res = await this.$send(userParams)
      if (res.meta.status === 200) {
        this.$showMsg('修改成功')
      }
    },
    btnEditUser(user) {
      this.dialogEditVisible = true
      this.editForm = user
    },
    btnDeleteClick(user) {
      this.$confirm(`此操作将永久删除${user.username}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteUser(user)
      }).catch((err) => {
        console.log(err)
      })
    },
    async btnSettingClick(user) {
      const params = {
        url: '/roles',
        method: 'GET'
      }
      const res = await this.$send(params)
      if (res.meta.status === 200) {
        this.roleObj.roles = res.data
        this.roleObj.userId = user.id
        this.dialogChangeVisible = true
      }
    },
    async changeRole() {
      const roleParams = {
        url: `/users/${this.roleObj.userId}/role`,
        method: 'PUT',
        params: {
          rid: this.roleObj.roleId
        }
      }
      const res = await this.$send(roleParams)
      if (res.meta.status === 200) {
        this.$showMsg(res.meta.msg)
        this.getUsers()
        this.dialogChangeVisible = false
      }
    },
    async deleteUser(user) {
      const deleteParams = {
        url: `/users/${user.id}`,
        // url: '/user',
        method: 'DELETE',
        fullscreen: true
      }
      const res = await this.$send(deleteParams)
      if (res.meta.status === 200) {
        this.$showMsg(res.meta.msg)
        this.getUsers()
      }
    },
    async editUser(user) {
      const userEditParams = {
        url: `users/${user.id}`,
        method: 'PUT',
        params: user,
        fullscreen: true
      }
      const res = await this.$send(userEditParams)
      if (res.meta.status === 200) {
        this.$showMsg(res.meta.msg)
        this.dialogEditVisible = false
        this.editForm = {}
      }
    },
    addUser() {
      this.$refs.addFormRef.validate(async validate => {
        if (!validate) return
        const userAddParams = {
          url: 'users',
          method: 'POST',
          params: this.addForm,
          fullscreen: true
        }
        const res = await this.$send(userAddParams)
        if (res.meta.status === 200) {
          this.$showMsg(res.meta.msg)
          this.dialogAddVisible = false
        }
      })
    },
    // 监听用户对话框关闭
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 监听用户对话框关闭
    changeDialogClosed () {
      this.$refs.changeFormRef.resetFields()
    },
    // 监听用户对话框关闭
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    getUsersList() {
      this.queryData.query = ''
      this.getUsers()
    },
    handleCurrentChange(curPage) {
      this.queryData.pagenum = curPage
      this.getUsers()
    },
    handleSizeChange(pagesize) {
      this.queryData.pagesize = pagesize
      this.getUsers()
    },
    handlePrevChange(curPage) {
      this.queryData.pagenum = curPage
      this.getUsers()
    },
    handleNextChange(curPage) {
      this.queryData.pagenum = curPage
      this.getUsers()
    },
    getQueryAboutList() {
      this.getUsers()
    }
  }
}
</script>
